<?php
namespace app\api\controller;

use think\Controller;
use app\api\model\Postdatadb;

class Zhongzhi extends Controller
{

    protected $ys_config = [
        'geteway' => 'http://api.utecbj.com/erp/api/',
        'partnerId' => 25,
        'siteId' => 13,
        'appId' => 'utec',
        'appKey' => 'yserp',
        'appSecret' => 'duXtRelcYy2sJeqrLpmNvbQO0O0OO0O0O'
    ];

    protected $username = 'zhongzhi_admin';

    protected $password = '12345678';

    protected $member_id = 121;

    protected $site_url = 'http://zz.mall.utecbj.com/';

    protected $token = '72C8892219DE543FB60F7249EC934F7F';

    protected $client_id = '100001845';

    public $request = array();

    public function _initialize()
    {
        header("Access-Control-Allow-Origin: *");
        // header('Content-Type:application/json; charset=utf-8');
        $request = request();
        $this->request = json_decode($request->getInput(), true);
        // dump($request->getInput());
        // 捕获请求的数据
        $postdatadb = new Postdatadb();
        $postdatadb->param['post_json'] = $this->request;
        $postdatadb->param['post_url'] = $request->url();
        $postdatadb->ajaxSave();
    }

    public function index()
    {
        exit('欢迎使用');
    }

    protected function ajaxReturn($return, $json_option = JSON_UNESCAPED_UNICODE)
    {
        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($return, $json_option));
    }

    protected function sendInfo($string_uri, $post)
    {
        $post['config'] = $this->ys_config;
        $json_data = json_encode($post);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->ys_config['geteway'] . $string_uri);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-type: application/json;charset='utf-8'"
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }
    // 获取token
    public function getToken()
    {
        if (! isset($this->request['key']) || $this->request['key'] != $this->client_id) {
            $this->ajaxReturn(array(
                'error' => '用户编号错误'
            ));
        }
        $this->ajaxReturn(array(
            'token' => $this->token
        ));
    }
    // 获取商品池
    public function queryProdPool()
    {
        if (! isset($this->request['queryProdPool']['categoryId'])) {
            $this->ajaxReturn(array(
                'error' => '品类标识错误'
            ));
        }
        $post_category['api_option'] = $this->request['queryProdPool']['categoryId'];
        $get_category = $this->sendInfo('apiCategory', $post_category);
        $category_sign3 = array();
        foreach ($get_category['data'] as $key => $val) {
            array_push($category_sign3, $val['category_sign']);
        }
        if (count($category_sign3) == 0) {
            $this->ajaxReturn(array(
                'error' => '该品类下没有商品'
            ));
        }
        $post['where']['category_sign3'] = $category_sign3;
        $post['page']['page'] = 1;
        $post['page']['limit'] = 10000;
        $post['sort']['_o'] = 'create_time';
        $post['sort']['_b'] = 'asc';
        $post['no_need_handle_data'] = 'yes';
        $data = $this->sendInfo('goodsList', $post);
        $return['queryProdPool']['success'] = array();
        foreach ($data['data'] as $key => $val) {
            $temp['skuId'] = $val['goods_sku'];
            $temp['cmmdtyType'] = 1;
            array_push($return['queryProdPool']['success'], $temp);
        }
        $this->ajaxReturn($return);
    }
    // 商品详情
    public function getProdDetail()
    {
        if (! isset($this->request['getProdDetail']['skuId'])) {
            $this->ajaxReturn(array(
                'error' => 'skuId错误'
            ));
        }
        $post['goods_sku'] = $this->request['getProdDetail']['skuId'];
        $post['member_id'] = $this->member_id;
        $post['no_more_price'] = 'yes';
        // $post['no_need_goods_handle'] = 'yes';
        $post['no_need_attr'] = 'yes';
        $data = $this->sendInfo('goodsOnlyDetail', $post);
        if (count($data['data']) == 1) {
            $this->ajaxReturn(array(
                'error' => '没有找到对应的商品信息'
            ));
        }
        $datas['skuId'] = $data['data']['goods_sku'];
        $datas['weight'] = $data['data']['weight'] ? $data['data']['weight'] : "";
        $datas['image'] = $data['data']['goods_picture']['save_path'];
        $datas['brand'] = $data['data']['brand_name'];
        $datas['model'] = $data['data']['goods_model'];
        $datas['name'] = $data['data']['goods_name'];
        $datas['upc'] = $data['data']['upc'] ? $data['data']['upc'] : "";
        $datas['saleUnit'] = $data['data']['goods_unit'];
        $datas['category'] = $data['data']['category_api_option'];
        $datas['introduction'] = $data['data']['goods_content'];
        $datas['state'] = $data['data']['sale_state'] == 1 ? 1 : 0;
        $this->ajaxReturn(array(
            'getProdDetail' => $datas
        ));
    }
    // 获取商品图片地址
    public function getProdPictures()
    {
        if (! isset($this->request['skuIds']) || count($this->request['skuIds']) == 0) {
            $this->ajaxReturn(array(
                'error' => 'skuId错误'
            ));
        }
        $skuIds = array();
        foreach ($this->request['skuIds'] as $key => $val) {
            array_push($skuIds, $val['skuId']);
        }
        $post['goods_sku'] = $skuIds;
        $data = $this->sendInfo('goodsPicture', $post);
        $return = array();
        foreach ($data['data'] as $key => $val) {
            $i = 0;
            $success['urls'] = array();
            foreach ($val['goods_pictures'] as $k => $v) {
                $temp['primary'] = $i ++ == 0 ? 1 : 0;
                $i ++;
                $temp['path'] = $v['save_path'];
                array_push($success['urls'], $temp);
            }
            $success['skuId'] = $val['goods_sku'];
            array_push($return, $success);
        }
        $this->ajaxReturn(array(
            'queryProdImage' => $return
        ));
    }
    // 商品上下架状态
    public function onShelvesList()
    {
        if (! isset($this->request['skuIds']) || count($this->request['skuIds']) == 0) {
            $this->ajaxReturn(array(
                'error' => 'skuId错误'
            ));
        }
        $skuIds = array();
        foreach ($this->request['skuIds'] as $key => $val) {
            array_push($skuIds, $val['skuId']);
        }
        $post['where']['goods_sku'] = $skuIds;
        $post['sort']['_o'] = 'goods_sku';
        $post['sort']['_b'] = 'asc';
        $post['page']['page'] = 1;
        $post['page']['limit'] = 1000;
        $post['no_more_price'] = 'yes';
        $post['no_need_handle_data'] = 'yes';
        $post['need_attr'] = 'yes';
        $post['sale_state'] = array(
            1,
            0
        );
        $data = $this->sendInfo('goodsList', $post);
        $result['onShelvesList']['success'] = array();
        foreach ($data['data'] as $key => $val) {
            $temp['skuId'] = $val['goods_sku'];
            $temp['state'] = $val['sale_state'] == 1 ? 1 : 0;
            array_push($result['onShelvesList']['success'], $temp);
        }
        $this->ajaxReturn($result);
    }
    // 商品价格
    public function queryPrice()
    {
        if (! isset($this->request['queryPrice']['skus']) || count($this->request['queryPrice']['skus']) == 0) {
            $this->ajaxReturn(array(
                'error' => 'skuId错误'
            ));
        }
        $skuIds = array();
        foreach ($this->request['queryPrice']['skus'] as $key => $val) {
            array_push($skuIds, $val['skuId']);
        }
        $post['goods_sku'] = $skuIds;
        $data = $this->sendInfo('goodsPrice', $post);
        $result['queryPrice']['success'] = array();
        foreach ($data['data'] as $key => $val) {
            $temp['skuId'] = $val['goods_sku'];
            $temp['price'] = $val['api_price'];
            $temp['rfPrice'] = $val['market_price'];
            $temp['discountRate'] = ceil((floatval($val['market_price']) - floatval($val['api_price'])) / floatval($val['market_price']) * 100) . '%';
            array_push($result['queryPrice']['success'], $temp);
        }
        $this->ajaxReturn($result);
    }
    // 库存查询
    public function queryMpStock()
    {
        if (! isset($this->request['queryMpStock']['skuIds']) || count($this->request['queryMpStock']['skuIds']) == 0) {
            $this->ajaxReturn(array(
                'error' => 'skuId错误'
            ));
        }
        $skuIds = array();
        $nums = array();
        foreach ($this->request['queryMpStock']['skuIds'] as $key => $val) {
            array_push($skuIds, $val['skuId']);
            array_push($nums, $val['num']);
        }
        $post['goods_sku'] = $skuIds;
        $data = $this->sendInfo('goodsPrice', $post);
        $result['queryMpStock']['success'] = array();
        $i = 0;
        foreach ($data['data'] as $key => $val) {
            $temp['skuId'] = $val['goods_sku'];
            $temp['state'] = '00'; // 00 有货,00：有货01：暂不销售 02：无货 03：库存不足
            if (intval($val['view_stock']) < intval($nums[$i])) {
                $temp['state'] = '03';
            }
            $i ++;
            array_push($result['queryMpStock']['success'], $temp);
        }
        $this->ajaxReturn($result);
    }
    // 创建订单
    public function addOrder()
    {
        if (! isset($this->request['addOrder'])) {
            $this->ajaxReturn(array(
                'error' => '订单号错误1'
            ));
        }
        // 加入购物车
        foreach ($this->request['addOrder']['sku'] as $key => $val) {
            $post_cart['set_sale_price'] = 'yes';
            $post_cart['goods_sku'] = $val['skuId'];
            $post_cart['buy_num'] = $val['num'];
            $post_cart['member_id'] = $this->member_id;
            $post_cart['no_need_goods_handle'] = 'yes';
            $post_cart['no_need_attr'] = 'yes';
            $data_cart = $this->sendInfo('addCart', $post_cart);
        }
        // 配送地址
        $post_addr['field']['province'] = $this->request['addOrder']['provinceId'];
        $post_addr['field']['city'] = $this->request['addOrder']['cityId'];
        $post_addr['field']['area'] = $this->request['addOrder']['countyId'];
        $post_addr['field']['street'] = $this->request['addOrder']['townId'] . $this->request['addOrder']['address'];
        $post_addr['field']['phone'] = $this->request['addOrder']['mobile'];
        $post_addr['field']['contacts'] = $this->request['addOrder']['receiverName'];
        $post_addr['member_id'] = $this->member_id;
        $data_addr = $this->sendInfo('saveApiAddress', $post_addr);
        // 下单
        $post_order['member_id'] = $this->member_id;
        $order_info['shopping_id'] = $data_addr;
        $order_info['pay_type'] = 'zhangqi';
        $order_info['member_id'] = $this->member_id;
        $order_info['site_id'] = $this->ys_config['siteId'];
        $order_info['delivery_date'] = date('Y-m-d H:i:s', time() + 86400 * 3);
        $order_info['remark'] = $this->request['addOrder']['remark'];
        $order_info['out_order_no'] = $this->request['addOrder']['tradeNo'];
        $order_info['api_param'] = json_encode($this->request['addOrder']);
        $order_info['order_money'] = $this->request['addOrder']['amount'] * 100;
        $order_info['is_invoice'] = 3;
        if ($this->request['addOrder']['invoiceState'] == 1) {
            $order_info['is_invoice'] = 2;
            if ($this->request['addOrder']['invoiceType'] == 1 || $this->request['addOrder']['invoiceType'] == 6) {
                $order_info['invoice_type'] = 3;
            } elseif ($this->request['addOrder']['invoiceType'] == 2) {
                $order_info['invoice_type'] = 1;
            } else {
                $order_info['invoice_type'] = 2;
            }
            $order_info['invoice_title'] = $this->request['addOrder']['invoiceTitle'];
            $order_info['invoice_duty'] = $this->request['addOrder']['taxno'];
            $order_info['invoice_addr'] = $this->request['addOrder']['invoiceAddr'];
            $order_info['invoice_tel'] = $this->request['addOrder']['telephone'];
            $order_info['invoice_bank'] = $this->request['addOrder']['invoiceBank'];
            $order_info['invoice_account'] = $this->request['addOrder']['invoiceAccount'];
            $order_info['invoice_money'] = $order_info['order_money'];
            $order_info['invoice_content'] = $this->request['addOrder']['invoiceContent'];
        }
        $post_order['order_info'] = $order_info;
        $data = $this->sendInfo('createOrder', $post_order);
        $result['orderId'] = $data['data'];
        $result['amount'] = $this->request['addOrder']['amount'];
        $result['freight'] = "0.00";
        $result['skus'] = array();
        $get_cart_post['member_id'] = $this->member_id;
        $get_cart_post['order_no'] = $data['data'];
        $get_cart_list = $this->sendInfo('orderCartList', $get_cart_post);
        foreach ($get_cart_list['data']['list'] as $key => $val) {
            $temp['orderItemId'] = $val['cart_id'];
            $temp['skuId'] = $val['goods_sku'];
            $temp['num'] = $val['goods_num'];
            $temp['arriveData'] = $order_info['delivery_date'];
            $temp['price'] = $val['goods_price'];
            $temp['rfPrice'] = $val['goods_sale_price'];
            $temp['discountRate'] = ceil((floatval($val['goods_sale_price']) - floatval($val['goods_price'])) / floatval($val['goods_sale_price']) * 100) . '%';
            array_push($result['skus'], $temp);
        }
        $this->ajaxReturn(array(
            'addOrder' => $result
        ));
    }
    // 取消订单
    public function addConfirmOrder()
    {
        if (! isset($this->request['addConfirmOrder']['orderId'])) {
            $this->ajaxReturn(array(
                'error' => '订单号错误'
            ));
        }
        $post['order_no'] = $this->request['addConfirmOrder']['orderId'];
        $post['member_id'] = $this->member_id;
        $data = $this->sendInfo('cancelOrder', $post);
        $result['deleteRejectOrder']['unCampSuccess'] = 'Y';
        $this->ajaxReturn($result);
    }
    // 查询订单信息
    public function getOrderDetail()
    {
        if (! isset($this->request['getOrderDetail']['orderId'])) {
            $this->ajaxReturn(array(
                'error' => '订单号错误'
            ));
        }
        $post['order_no'] = $this->request['getOrderDetail']['orderId'];
        $post['member_id'] = $this->member_id;
        $post['need_express_info'] = 'no';
        $post['no_more_price'] = 'yes';
        $data = $this->sendInfo('getOrderDetail', $post);
        $api_json = json_decode($data['data']['api_param'], true);
        $result['companyName'] = isset($api_json['invoiceTitle']) ? $api_json['invoiceTitle'] : $api_json['companyCustNo'];
        $result['orderAmt'] = $api_json['amount'];
        $result['createTime'] = $data['data']['create_time'];
        $result['accountName'] = $api_json['companyCustNo'];
        $result['receiverTel'] = $api_json['mobile'];
        $result['receiverAddress'] = $api_json['provinceId'] . $api_json['cityId'] . $api_json['countyId'] . $api_json['townId'] . $api_json['address'];
        $result['orderItemList'] = array();
        foreach ($data['data']['cart_info'] as $key => $val) {
            $temp['orderItemId'] = $val['cart_id'];
            $temp['orderId'] = $data['data']['order_no'];
            $temp['commdtyName'] = $val['goods_info']['goods_name'];
            $temp['commdtyCode'] = $val['goods_sku'];
            $temp['skuNum'] = $val['goods_num'];
            $temp['unitPrice'] = $val['goods_price'];
            $temp['skuAmt'] = $val['goods_price'] * $val['goods_num'];
            $temp['brandName'] = $val['goods_info']['brand_name'];
            array_push($result['orderItemList'], $temp);
        }
        $this->ajaxReturn(array(
            'getOrderDetail' => $result
        ));
    }
    // 获取订单状态
    public function getOrderStatus()
    {
        if (! isset($this->request['getOrderStatus']['orderId'])) {
            $this->ajaxReturn(array(
                'error' => '订单号错误'
            ));
        }
        $post['order_no'] = $this->request['getOrderStatus']['orderId'];
        $post['member_id'] = $this->member_id;
        $post['need_express_info'] = 'no';
        $post['need_goods_info'] = 'no';
        $data = $this->sendInfo('getOrderDetail', $post);
        $result['orderId'] = $this->request['getOrderStatus']['orderId'];
        $result['orderStatus'] = 1; // 订单状态
                                    // 订单状态：1下单，2确认订单，3订单发货，4订单收货,5订单完成,-1取消订单
        switch ($data['data']['order_state']) {
            case 1:
                $result['orderStatus'] = 1;
                break;
            case 2:
                $result['orderStatus'] = 2;
                break;
            case 3:
                $result['orderStatus'] = 3;
                break;
            case 4:
            case 5:
                $result['orderStatus'] = 5;
                break;
            case - 1:
                $result['orderStatus'] = 6;
                break;
        }
        $result['orderItemInfoList'] = array();
        foreach ($data['data']['cart_info']['list'] as $key => $val) {
            $temp['orderItemId'] = $val['cart_id'];
            $temp['skuId'] = $val['goods_num'];
            $temp['statusName'] = $result['orderStatus'] >= 4 ? $result['orderStatus'] - 1 : $result['orderStatus'];
            array_push($result['orderItemInfoList'], $temp);
        }
        $this->ajaxReturn(array(
            'getOrderStatus' => $result
        ));
    }
    // 订单物流信息
    public function getOrderLogist()
    {
        if (! isset($this->request['getOrderLogist']['orderId'])) {
            $this->ajaxReturn(array(
                'error' => '订单号错误'
            ));
        }
        $post['order_no'] = $this->request['getOrderLogist']['orderId'];
        $post['member_id'] = $this->member_id;
        $post['need_express_info'] = 'no';
        $post['need_goods_info'] = 'no';
        $data = $this->sendInfo('getOrderDetail', $post);
        $result['orderId'] = $this->request['getOrderLogist']['orderId'];
        $result['orderItemId'] = $this->request['getOrderLogist']['orderItemId'];
        $result['skuId'] = $this->request['getOrderLogist']['skuId'];
        $result['orderLogisticStatus'] = array();
        $temp['operateState'] = '创建订单';
        $temp['operateTime'] = $data['data']['create_time'] . ':00';
        array_push($result['orderLogisticStatus'], $temp);
        if ($data['data']['order_state'] == - 1) {
            $temp['operateState'] = '订单已取消';
            $temp['operateTime'] = $data['data']['cancel_time'] . ':00';
            array_push($result['orderLogisticStatus'], $temp);
        }
        if ($data['data']['order_state'] > 1) {
            $temp['operateState'] = '确认订单';
            $temp['operateTime'] = $data['data']['confirm_time'] . ':00';
            array_push($result['orderLogisticStatus'], $temp);
        }
        if ($data['data']['order_state'] > 2) {
            $temp['operateState'] = '商品已发货';
            $temp['operateTime'] = $data['data']['shopping_time'] . ':00';
            array_push($result['orderLogisticStatus'], $temp);
            $result['shippingTime'] = $data['data']['shopping_time'] . ':00';
        }
        if ($data['data']['order_state'] > 3) {
            $temp['operateState'] = '商品已收';
            $temp['operateTime'] = $data['data']['receipt_time'] . ':00';
            array_push($result['orderLogisticStatus'], $temp);
            $result['receiveTime'] = $data['data']['receipt_time'] . ':00';
        }
        $back = array();
        array_push($back, $result);
        $this->ajaxReturn(array(
            'getOrderLogist' => $back
        ));
    }
    // 运费
    public function getShipTime()
    {
        $this->ajaxReturn(array(
            'getShipCarriage' => array(
                'freightFare' => 0
            )
        ));
    }
    // 补开发票
    public function confirmInvoice()
    {
        if (! isset($this->request['confirmInvoice']['orderInfoDTO'])) {
            $this->ajaxReturn(array(
                'error' => '发票信息错误'
            ));
        }
        $get_order_item = array();
        foreach ($this->request['confirmInvoice']['orderInfoDTO'] as $key => $val) {
            array_push($get_order_item, $val['gcOrderNo']);
        }
        $post_invoice['order_no'] = $get_order_item;
        $data_invoice_state = $this->sendInfo('editOrderInvoice', $post_invoice);
        $post_order['member_id'] = $this->member_id;
        $post_order['order_no'] = $get_order_item;
        $post_order['need_goods_title'] = 'yes';
        $get_cart_list = $this->sendInfo('orderCartList', $post_order);
        $invoice_info = $this->request['confirmInvoice']['applyForInvoiceReqDTO'];
        $all_money = 0;
        $cart_ids = array();
        $result = array();
        foreach ($get_cart_list['data']['list'] as $key => $val) {
            $all_money += $val['goods_price'] * $val['goods_num'];
            array_push($cart_ids, $val['cart_id']);
            $temp['gcOrderNo'] = $val['order_no'];
            $temp['orderNo'] = $val['cart_id'];
            $temp['skuId'] = $val['goods_sku'];
            $temp['skuName'] = $val['goods_name'];
            $temp['invoiceAmount'] = $val['goods_num'] * $val['goods_price'];
            $temp['invoiceType'] = $invoice_info['invoiceType'];
            $temp['invoiceStatus'] = 1;
            $temp['status'] = 1;
            array_push($result, $temp);
        }
        $post['member_id'] = $this->member_id;
        $post['invoice_type'] = $invoice_info['invoiceType'] == 2 ? 1 : 3; // 发票类型
        $post['invoice_title'] = $invoice_info['title'];
        $post['invoice_duty'] = $invoice_info['taxNo'];
        $post['invoice_addr'] = $invoice_info['address'];
        $post['invoice_tel'] = $invoice_info['regTel'];
        $post['invoice_bank'] = $invoice_info['regBank'];
        $post['invoice_account'] = $invoice_info['regAccount'];
        $post['invoice_money'] = $all_money * 100; // 发票金额
        $post['cart_ids'] = implode(',', $cart_ids); // 购物车号
        $post['order_nos'] = implode(',', $get_order_item); // 订单号
        $post['state'] = 1;
        $post['invoice_content'] = $invoice_info['invoiceContent'];
        $data = $this->sendInfo('addInvoice', $post);
        $return['sn_responseContent']['sn_body']['confirmInvoice']['allOrderItemList'] = $result;
        $this->ajaxReturn($return);
    }
    // 获取商品参数
    public function configList()
    {
        if (! isset($this->request['skuIds'])) {
            $this->ajaxReturn(array(
                'error' => '商品编号错误'
            ));
        }
        $result['success'] = array();
        foreach ($this->request['skuIds'] as $key => $val) {
            $post['goods_sku'] = $val['skuId'];
            $post['site_id'] = $this->ys_config['siteId'];
            $data = $this->sendInfo('goodsAttrValue', $post);
            foreach ($data['data'] as $k => $v) {
                $temp['skuId'] = $val['skuId'];
                $temp['configNm'] = $v['attr_name'];
                $temp['configValue'] = $v['attr_value'];
                array_push($result['success'], $temp);
            }
        }
        $this->ajaxReturn(array(
            'onConfigList' => $result
        ));
    }
    // 获取电子发票地址
    public function getInvoiceList()
    {
        if (! isset($this->request['getOrderStatus']['orderId'])) {
            $this->ajaxReturn(array(
                'error' => '订单号错误'
            ));
        }
        $post['order_no'] = $this->request['getOrderStatus']['orderId'];
        $data = $this->sendInfo('getInvoiceInfo', $post);
        if ($data['count'] == 0) {
            $this->ajaxReturn(array(
                'error' => '尚未开具电子发票'
            ));
        }
        if (! isset($data['data']['invoice_proof']) || ! $data['data']['invoice_proof']) {
            $this->ajaxReturn(array(
                'error' => '尚未开具电子发票'
            ));
        }
        $result['orderId'] = $this->request['getOrderStatus']['orderId'];
        $result['invoiceUrl'] = $data['data']['invoice_proof']['save_path'];
        $this->ajaxReturn(array(
            'getOrderStatus' => $result
        ));
    }
}